package com.hnevc.foodserver.service;

import com.hnevc.foodserver.bean.Foods;
import com.hnevc.foodserver.dao.FoodsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;


import java.util.List;
@Service
public class FoodsService {
    @Autowired
    FoodsDao foodsDao;
    public List<Foods> list(){
        List<Foods> all = foodsDao.findAll();
        return all;
    }

    public Foods findone(Foods foods) {
        Foods foods1 = foodsDao.findOne(Example.of(foods)).orElse(null);
        return foods1;
    }

    public boolean deleteById(Integer id) {
        try {
            foodsDao.deleteById(id);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public Foods updateFood(Foods food) {
        Foods saved = foodsDao.save(food);
        return saved;
    }

    public Page<Foods> getFoodByPage(PageRequest page) {
        return foodsDao.findAll(page);
    }

    public Foods uploadIcon(Integer id, String filePath) {
        if (foodsDao.existsById(id)) {
            Foods foods = foodsDao.findById(id).orElse(null);
            if(foods!=null) {
                foods.setIcon(filePath);
                Foods saved = foodsDao.save(foods);
                return saved;
            }else {
                return null;
            }
        }else{
            return  null;
        }
    }
}
